package com.chuangjiangx.member.basic.web.controller;

import com.chuangjiangx.commons.RestTemplates;
import com.chuangjiangx.commons.response.CamelResponse;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.domain.shared.model.PayEntry;
import com.chuangjiangx.member.coupon.web.response.response.ADResponse;
import com.chuangjiangx.member.basic.ddd.query.MerchantInfoQuery;
import com.chuangjiangx.member.basic.ddd.query.dto.MerchantInfoDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;

/**
 * @author cj-yzh
 * @date 2018/8/14 下午5:37
 */
@Api(tags = "广告")
@RestController
@RequestMapping("/h5/ad")
public class ADController {

    @Autowired
    private MerchantInfoQuery merchantInfoQuery;

    @Value("${advertising.api.domain}")
    private String advertisingApiDomain;


    @RequestMapping(value = "/query-url/{merchantId}" , method = RequestMethod.GET)
    @ApiOperation(value = "查询广告地址接口")
    public CamelResponse<String> getAdvertisingUrl(
            @PathVariable Long merchantId
    ){
        //TODO 暂时写死成微信的
        PayEntry entry = PayEntry.WXPAY;
        String adURL = "";
        MerchantInfoDTO merchantInfoDTO = merchantInfoQuery.searchMerchantInfoForH5(merchantId);
        if(null != merchantInfoDTO){
            String regionCoding = merchantInfoDTO.getProvince()+","+merchantInfoDTO.getCity();
            if(StringUtils.isNotBlank(advertisingApiDomain)){
                ADResponse adResponse = null;
                try {
                    adResponse = RestTemplates.INS
                            .getForObject("{host}/api/advertising/get-the-tactics?payEntry={PayEntry}&regionCoding={regionCoding}",
                                    ADResponse.class,advertisingApiDomain,entry.value,regionCoding);
                } catch (RestClientException e) {
                    e.printStackTrace();
                }
                if(adResponse != null){
                    int hasTactics = adResponse.getHasTactics();
                    if (hasTactics == 1){
                        adURL = advertisingApiDomain+"/api/advertising/redirect?payEntry="+entry.value+"&regionCoding="+regionCoding;
                    }
                }
            }
        }

        return (CamelResponse<String>)ResponseUtils.successCamel(adURL);


    }





}
